<template>
  <div style="min-height: 470px">
    <el-form ref="roleForm" :model="entity" :rules="rules" label-width="120px"  @submit.native.prevent>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="entity.roleName" @keyup.enter.native="btnSubmit" ref="roleName" placeholder="角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="btnSubmit" size="default">确 定</el-button>
        <el-button @click="onCancel" size="default">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="roleDetail">
import request from '/@/utils/request';
import { ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick} from "vue";

// 定义变量内容
const roleForm = ref(null);
const roleName = ref(null);

const emit = defineEmits(['update:modelValue'])
let props = defineProps({
  modelValue : {type : Boolean, default: true},
  entityId : {type : Number, default: 0}
})

let entity = ref({
  roleName: '',
})
const rules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
})

const loadEntity = ()=>{
  if(props.entityId > 0){
    request({ url: '/sys/role/getrole', data: {id : props.entityId} }).then( res =>{
      entity.value = res.data
    })
  }
}
const onCancel = ()=>{
  emit('update:modelValue', false) //关闭弹窗
}
const btnSubmit = ()=>{
  if(!roleForm.value) return;
  roleForm.value.validate((valid)=>{
    if(valid){
      request({
        url: '/sys/role/addeditrole',
        data: entity.value
      }).then( res =>{
        if(res.code === "200"){
          ElMessage.success(res.msg)
          emit('update:modelValue', false) //关闭弹窗
          props.entityId > 0 ? mittBus.emit('roleedit', {}) : mittBus.emit('roleadd', {}); //触发事件总线，让列表界面更新数据
        }else{
          ElMessage.error(res.msg);
        }
      })
    }else {
      console.log('error submit!!');
      return false;
    }
  })
}

onMounted(() => {
  loadEntity();
  nextTick(()=>{
    roleName.value.focus()
  })
});
</script>
